import type { SYSTEM_CONFIG } from '@/global/enum/common';
import type { SysConfig } from '@/views/modules/tool/system-setting/data/types';
import { message } from 'ant-design-vue';
import { clearCacheKey } from '../../monitor/cache/cache';
import { pageSettings } from '../../public/public';
import { encryptedStorage } from './config';

/**
 * @description:
 *  根据键名获取字典里的对象
 *  如果没有值的，则用obj进行初始化
 * @param {any} obj
 */
export const getConfig = async (obj: SysConfig): Promise<SysConfig | undefined> => {
  try {
    const { data } = await pageSettings();
    if (!data.data?.config) return obj;
    let { config } = data.data;
    if (Object.keys(config).length === 0) {
      config = obj;
    } else {
      Object.keys(obj).forEach(v => {
        if (!(config as any)[v]) {
          config[v] = (obj as any)[v];
        }
      });
    }
    return config;
  } catch (error) {}
};

/**
 * @description: 保存配置
 * @param {string} configKey 键值
 * @param {string} jsonData 数据
 */
export const saveConfig = async (configKey: SYSTEM_CONFIG, jsonData: string) => {
  try {
    const { data } = await encryptedStorage(configKey, jsonData);
    if (data.code === 200) {
      message.info('保存成功');
    }
    await clearCacheKey(`sys_config:${configKey}`);
  } catch (error) {}
};
